package doinbackground;

import bean.BeanColumn;
import core.Config;
import core.db.DbHelper;
import core.task.async.bean.Param;
import core.task.async.bean.Result;
import core.task.async.callback.IWorker;
import core.task.async.wrapper.WorkerWrapper;
import util.CommonUtil;
import util.JsonXmlUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InitDbTask implements IWorker<Param, Result> {

    private String configFile = "config.ini";
    @Override
    public Result action(Param param, Map<String, WorkerWrapper> allWrappers) {
        DbHelper.getInstance();
        String resRoot = param.get();
        Map<String,String> config = CommonUtil.getConfig(resRoot+configFile);
        if(config!=null){
            if(!config.get("dbVersion").equals(Config.dbVersion)){
                config.put("dbVersion",Config.dbVersion+"");
                CommonUtil.saveConfig(resRoot+configFile,config);
                updateDb();
            }
        }else{
            config = new HashMap<>();
            config.put("dbVersion",Config.dbVersion+"");
            CommonUtil.saveConfig(resRoot+configFile,config);
        }
        return Result.put(config);
    }
    private void updateDb(){
        Map<String, List<String>> tabColumn = new HashMap<>();
        Map<String, List<BeanColumn>> claColumn = new HashMap<>();
        for (int i = 0; i < DbHelper.getTables().size(); i++) {
            Class cla = DbHelper.getTables().get(i);
            String claName = cla.getName();
            try {
                Class<?> c = Class.forName(claName);
                if (DbHelper.tableIsExist(c)) {
                    List<String> column = DbHelper.getTableCloumn(c);
                    String tableName = DbHelper.getTableName(c);
                    //设置表结构
                    tabColumn.put(tableName, column);
                    //获取类字段及类型，并转化成sqlite的类型
                    List<BeanColumn> clas = new ArrayList<>();
                    Field[] f = cla.getDeclaredFields();
                    for (Field field : f) {
                        String fildName = field.getName();
                        char firstChar = fildName.charAt(0);
                        if (Character.isUpperCase(firstChar)) {
                            continue;
                        }
                        if (fildName.equals("serialVersionUID")
                                || fildName.equals("id")
                                || fildName.equals("$change")) {
                            continue;
                        }

                        String fildType = field.getType().toString();
                        //过滤掉接口类型
                        if (fildType.startsWith("interface")) {
                            continue;
                        }
                        if (fildType.startsWith("class")) {
                            if (fildType.contains(".")) {
                                fildType = fildType.substring(fildType.lastIndexOf(".") + 1, fildType.length());
                            }
                            fildType = fildType.toLowerCase();
                        }
                        //类型转换
                        switch (fildType) {
                            case "string":
                                fildType = "TEXT";
                                break;
                            case "int":
                            case "integer":
                            case "long":
                            case "boolean":
                            case "date":
                                fildType = "INTEGER";
                                break;
                            case "float":
                            case "double":
                                fildType = "REAL";
                                break;
                            default:
                                continue;
                        }

                        BeanColumn beanColumn = new BeanColumn();
                        beanColumn.setName(fildName);
                        beanColumn.setType(fildType);

                        clas.add(beanColumn);
                    }
                    claColumn.put(tableName, clas);
                }
            } catch (Exception e) {
            }
        }
        //去除已存在的字段
        for (String key : tabColumn.keySet()) {
            for (String cKey : claColumn.keySet()) {
                if (key.equals(cKey)) {
                    List<String> column = tabColumn.get(key);
                    List<BeanColumn> beanColumns = claColumn.get(cKey);
                    for (int i = 0; i < column.size(); i++) {
                        for (int j = 0; j < beanColumns.size(); j++) {
                            if (column.get(i).equals(beanColumns.get(j).getName())) {
                                claColumn.get(cKey).remove(j);
                            }
                        }
                    }
                }
            }
        }

        //更新新增的字段
        for (String key : claColumn.keySet()) {
            List<BeanColumn> columns = claColumn.get(key);
            if (claColumn != null && columns.size() > 0) {
                for (int i = 0; i < columns.size(); i++) {
                    String sql = "ALTER TABLE " + key + " ADD COLUMN " + columns.get(i).getName() + " " + columns.get(i).getType();
                    DbHelper.exec_nonquery(sql);
                    try {
                        Thread.sleep(30);
                    }catch (Exception e){

                    }
                }

            }
        }
        DbHelper.initData();
    }
}
